跳到主要内容

结构模式-适配器模式

什么是适配器模式?

适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁

  • Adapter(适配器接口):即目标角色,定义把其他类转换为何种接口,也就是我们期望的接口。
  • Service(被适配角色):即源角色,一般是已存在的类,需要适配新的接口。
classDiagram Client --> Target Target <|.. Adapter Adapter *--> Service Target: <<interface>> Target: +request() Adapter: +request() Adapter: -Service service Service: +specificRequest()

使用示例

// 用户期待的接口
interface Target {
void request();
}
// 需要被适配的类
class Service {
public void specificRequest() {
System.out.println("需要被适配的方法")
}
}
// 适配器
class Adapter implements Target {
private Service service = new Service();

public void request() {
service.specificRequest();
}
}
// demo
public static void main(String[] args) {
Target target = new Adapter();
target.request();
}